package com.gylang.springmini.registry;

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author gylang
 * data 2021/11/15
 */
public class SimpleAliasRegistry implements AliasRegistry {

    private Map<String, String> alias2Name = new HashMap<>();
    private MultiValueMap<String, String> name2Alias = new LinkedMultiValueMap<>();

    @Override
    public void registerAlias(String name, String alias) {
        alias2Name.put(alias, name);
        name2Alias.add(name, alias);
    }

    @Override
    public void removeAlias(String alias) {
        Optional.ofNullable(name2Alias.get(alias2Name.get(alias))).ifPresent(a -> a.remove(alias));
        alias2Name.remove(alias);

    }
    @Override
    public void removeName(String name) {
        alias2Name.remove(name);

    }

    @Override
    public boolean isAlias(String name) {
        return alias2Name.containsKey(name);
    }

    @Override
    public String[] getAliases(String name) {
        return name2Alias.get(name).toArray(new String[0]);
    }

    @Override
    public String canonicalName(String name) {

        if (name2Alias.containsKey(name)) {
            return name;
        } else {
            return alias2Name.get(name);
        }
    }
}
